import * as cacheTypes from './cache-types';

export type TStatus = 'CREATE' | 'CREATED' | 'ACTIVE' | 'DESTROY' | 'CLEARALL';

export interface ICacheReducerState {
  scrolls?: Record<any, any>;
  cacheId: string;
  element?: React.ReactNode;
  doms?: ChildNode[];
  status?: TStatus;
}

export interface ICacheRducerAction {
  type: TStatus;
  payload: ICacheReducerState;
}

const cacheReducer: React.Reducer<
  Record<string, ICacheReducerState>,
  ICacheRducerAction
> = (cacheStates = {}, { type, payload }) => {
  switch (type) {
    case cacheTypes.CREATE:
      return {
        ...cacheStates,
        [payload.cacheId]: {
          scrolls: {}, // 缓存滚动条，key: dom, value: scrollTop
          cacheId: payload.cacheId, // 缓存Id
          element: payload.element, // 需要渲染的虚拟DOM
          doms: undefined, // 当前的虚拟dom所对应的真实dom
          status: cacheTypes.CREATE, // 缓存状态
        },
      };
    case cacheTypes.CREATED:
      return {
        ...cacheStates,
        [payload.cacheId]: {
          ...cacheStates[payload.cacheId],
          doms: payload.doms,
          status: cacheTypes.CREATED,
        },
      };
    case cacheTypes.ACTIVE:
      return {
        ...cacheStates,
        [payload.cacheId]: {
          ...cacheStates[payload.cacheId],
          status: cacheTypes.ACTIVE,
        },
      };
    // destory也只是变更状态
    case cacheTypes.DESTROY:
      return {
        ...cacheStates,
        [payload.cacheId]: {
          ...cacheStates[payload.cacheId],
          status: cacheTypes.DESTROY,
        },
      };
    case cacheTypes.CLEARALL:
      return {};
    default:
      return cacheStates;
  }
};

export default cacheReducer;
